package com.gthncz.service;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 自定义身份认证组件
 * @author GT
 *
 */
public class TokenAuthenticationProvider implements AuthenticationProvider{
	
	private static final Logger log = LoggerFactory.getLogger(TokenAuthenticationProvider.class);

	@Autowired
	private UserDetailsService userService;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		log.warn("TokenAuthenticationProvider authentication: {}", authentication);
		
		/****************************************************
		 *  验证 用户名 & 密码
		 ****************************************************/
		String username = authentication.getName();
		String password = authentication.getCredentials().toString();
		
		// 从数据库中取出 用户 
		UserDetails user = userService.loadUserByUsername(username);
		
		log.warn("Authentication credential: {}", password);
		log.warn("user password: {}", user.getPassword());
		
		if(user != null && user.getUsername().equals(username) 
				&& user.getPassword().equals(password)) {
			//if ("admin".equals(username) && "123456".equals(password)) {
			// 在这里设置权限/角色
			// List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>() ;
			// authorities.add(new GrantedAuthorityImpl("AUTH_WRITE"));
			// authorities.add(new GrantedAuthorityImpl("ADMIN"));
			
			Collection<? extends GrantedAuthority> authorities =  user.getAuthorities();
			
			// 生成 token 
			Authentication auth = new UsernamePasswordAuthenticationToken(username, password, authorities);
			log.warn("TokenAuthenticationProvider gen authentication: {}", auth);
			
			return auth;
		} else {
			throw new BadCredentialsException("Bad Credentials.");
		}
		
	}

	// 是否可以提供输入类型的认证服务
	@Override
	public boolean supports(Class<?> authentication) {
		// 需要使用 equal 返回 true, 否则ProviderNotFoundException： No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken
		// 需要使用 UsernamePasswordAuthenticationToken
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
